<?php

namespace App\Repository\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

/**
 * Class OrderQualificationBid.
 *
 * @package namespace App\Repository\Models;
 */
class OrderQualificationBid extends Model implements Transformable
{
    use TransformableTrait;

    protected $table = 'order_qualification_bid';
    protected $fillable = ['id','service_code','shop_id','user_id','bid_date','project_name','project_inf','appendix','invoce_id','status','remark','expect_date'];

    public static function boot() {
         self::creating(function ($attri) {
             //资质编号: EPD+年(后2位)+月+日+店铺id（6位，前置补0）+6位流水 （如180315XXXXX000001）
             $shop_id_str = sprintf('%06s', $attri->shop_id);
             //店铺订单流水号，自增，取后6位
             $attri_order_serial = Redis::INCR('attri:order:serial:' . $attri->id) % 1000000;
             $attri_order_serial_fill = sprintf('%06s', $attri_order_serial);
             $attri->service_code = 'S'.date('ymd') .$shop_id_str . $attri_order_serial_fill;

         });
     }

    public function getExpectDateAttribute()
    {
        if (isset($this->attributes['expect_date'])) {
            return date('Y/m/d',strtotime($this->attributes['expect_date']));
        }
        return null;
    }

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
    public function shop()
    {
        return $this->hasOne(Shop::class, 'sp_id', 'shop_id');
    }

    public function service_detail()
    {
        return $this->hasMany(OrderQualificationDetail::class, 'bid_id', 'id');
    }

}
